<script setup lang="ts">
import { computed, reactive } from 'vue';
import { fetchResetPassword } from '@/service/api';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { $t } from '@/locales';

// eslint-disable-next-line vue/define-emits-declaration
const emit = defineEmits(['switch']);

defineOptions({
  name: 'ResetPwd'
});

const { formRef, validate } = useNaiveForm();

interface FormModel {
  phoneNumber: string;
  username: string;
  password: string;
  confirmPassword: string;
}

const model: FormModel = reactive({
  phoneNumber: '',
  username: '',
  password: '',
  confirmPassword: ''
});

type RuleRecord = Partial<Record<keyof FormModel, App.Global.FormRule[]>>;

const rules = computed<RuleRecord>(() => {
  const { formRules, createConfirmPwdRule } = useFormRules();

  return {
    phoneNumber: formRules.phone,
    username: formRules.userName,
    password: formRules.pwd,
    confirmPassword: createConfirmPwdRule(model.password)
  };
});

async function handleSubmit() {
  await validate();
  if (model.password !== model.confirmPassword) {
    window.$message?.error('两次输入的密码不一致');
    return;
  }
  try {
    const { error } = await fetchResetPassword(model.phoneNumber, model.username, model.password);
    if (!error) {
      window.$message?.success('密码重置成功！');
      emit('switch', 'pwd-login');
    } else {
      window.$message?.error(`密码重置失败：${error.message}`);
    }
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
  } catch (err) {
    window.$message?.error('密码重置失败，请稍后重试');
  }
}
</script>

<template>
  <NForm ref="formRef" :model="model" :rules="rules" size="large" :show-label="false" @keyup.enter="handleSubmit">
    <NFormItem path="phoneNumber">
      <NInput v-model:value="model.phoneNumber" :placeholder="$t('page.login.common.phonePlaceholder')" />
    </NFormItem>
    <NFormItem path="username">
      <NInput v-model:value="model.username" :placeholder="$t('page.login.common.userNamePlaceholder')" />
    </NFormItem>
    <NFormItem path="password">
      <NInput
        v-model:value="model.password"
        type="password"
        show-password-on="click"
        :placeholder="$t('page.login.common.passwordPlaceholder')"
      />
    </NFormItem>
    <NFormItem path="confirmPassword">
      <NInput
        v-model:value="model.confirmPassword"
        type="password"
        show-password-on="click"
        :placeholder="$t('page.login.common.confirmPasswordPlaceholder')"
      />
    </NFormItem>
    <NSpace vertical :size="18" class="w-full">
      <NButton type="primary" size="large" round block @click="handleSubmit">
        {{ $t('common.confirm') }}
      </NButton>
      <NButton size="large" round block @click="emit('switch', 'pwd-login')">
        {{ $t('page.login.common.back') }}
      </NButton>
    </NSpace>
  </NForm>
</template>

<style scoped></style>
